import ReqRateLimiter from '@/utils/reqRateLimiter';
import { warningMsg, errorMsg } from '@/utils/message';

const reqRateLimiter = new ReqRateLimiter();

export default function ({ $axios, redirect }) {
  const isProduction = process.env.NODE_ENV === 'production';

  $axios.defaults.baseURL = '/api';
  $axios.defaults.headers.common.Accept = 'application/json';

  $axios.onRequest(function (config) {
    reqRateLimiter.add(config);
  });

  $axios.onResponse(function ({ config, data }) {
    if (process.client) {
      reqRateLimiter.cancel(config);
      if (!data.success) {
        warningMsg(data.message);
      }
    }
  });

  $axios.onError(function (error) {
    const { config, response, message } = error;
    if (process.client) {
      // reqRateLimiter 取消请求信息
      if (message === 'request too frequently') {
        warningMsg('点击过于频繁');
        return;
      }
      reqRateLimiter.cancel(config);
      if (response.status === 401) {
        warningMsg(response.data.message || '没有权限');
        redirect('/login');
        return;
      }
      if (isProduction) {
        errorMsg('系統繁忙中...');
      } else {
        console.error('报错信息', response.data.message);
      }
    }
  });
}
